// productService.js

// 获取一级分类
export function fetchCategories() {
    return fetch('http://localhost:8080/category')
        .then(response => response.json())
        .catch(error => {
            console.error('获取一级分类失败:', error);
            throw error;
        });
}

// 获取二级分类
export function fetchSecondaryCategories(selectedPrimaryId) {
    const url = `http://localhost:8080/categories/${selectedPrimaryId}`;
    return fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .catch(error => {
            console.error('获取二级分类失败:', error);
            throw error;
        });
}

// 保存商品（发布或更新）
export function saveProductToServer(goodDto, imageFile) {
    const formData = new FormData();
    formData.append('good', new Blob([JSON.stringify(goodDto)], { type: 'application/json' }));
    if (imageFile) {
        formData.append('image', imageFile);
    }

    const url = goodDto.id ? `http://localhost:8080/good/update/${goodDto.id}` : 'http://localhost:8080/good/submit';
    const method = goodDto.id ? 'PUT' : 'POST';

    return fetch(url, {
        method: method,
        body: formData,
    })
        .then(response => response.json())
        .catch(error => {
            console.error('商品保存失败:', error);
            throw error;
        });
}

// 获取所有商品
export function fetchProducts() {
    return fetch('http://localhost:8080/good/list')
        .then(response => response.json())
        .catch(error => {
            console.error('获取商品列表失败:', error);
            throw error;
        });
}
